package com.example.demo.service.concurrent_shopping.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.Goods;
import com.example.demo.service.GoodsService;
import com.example.demo.service.concurrent_shopping.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 业务聚合
 *
 * @version [V2.0]
 * @package com.example.demo.service.concurrent_shopping.impl;
 * @description:[用一句话描述该文件做什么]
 * @author: [zhuben]
 * @date: [2021/7/22 9:12]
 * @copyright: 2021 echovin.com
 */

@Service
public class StockServiceImpl implements StockService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private GoodsService goodsService;

    @Override
    @PostConstruct
    public void preCacheStocks() {
        List<Goods> list = goodsService.list();
        if (null == list || list.isEmpty()) {
            return;
        }
        Map<Long, Goods> goodsMap = list.parallelStream().collect(Collectors.toMap(a -> a.getId(), a -> a));
        Set<Map.Entry<Long, Goods>> entries = goodsMap.entrySet();
        for (Map.Entry<Long, Goods> entry:entries){
            Long goodsId = entry.getKey();
            Goods goods = entry.getValue();
            redisTemplate.opsForHash().putIfAbsent("GOODS_STOCK", goodsId.toString(), JSONObject.toJSONString(goods));
        }
    }
}
